
/***
 * Easyui 网格单元格编辑
 */
$.extend($.fn.datagrid.methods, {
	editCell: function (jq, param) {
		return jq.each(function () {
			var opts = $(this).datagrid('options');
			var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
			for (var i = 0; i < fields.length; i++) {
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor1 = col.editor;
				if (fields[i] != param.field) {
					col.editor = null;
				}
			}
			$(this).datagrid('beginEdit', param.index);
			var ed = $(this).datagrid('getEditor', param);
			if (ed) {
				if ($(ed.target).hasClass('textbox-f')) {
					$(ed.target).textbox('textbox').focus();
				} else {
					$(ed.target).focus();
				}
			}
			for (var i = 0; i < fields.length; i++) {
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor = col.editor1;
			}
		});
	},
	enableCellEditing: function (jq) {
		return jq.each(function () {
			var dg = $(this);
			var opts = dg.datagrid('options');
			opts.oldOnClickCell = opts.onClickCell;
			opts.onClickCell = function (index, field) {
				if (opts.editIndex != undefined) {
					if (dg.datagrid('validateRow', opts.editIndex)) {
						dg.datagrid('endEdit', opts.editIndex);
						opts.editIndex = undefined;
					} else {
						return;
					}
				}
				dg.datagrid('selectRow', index).datagrid('editCell', {
					index: index,
					field: field
				});
				opts.editIndex = index;
				opts.oldOnClickCell.call(this, index, field);
			}
		});
	}
});

/**
*拓展datagrid的弹框编辑器
*
*/
$.extend($.fn.datagrid.methods, {
	initEditableDialog: function (jq, param) {
		var datagrid = $(jq);
		var row = datagrid.datagrid('getSelected');
		if (!row) {
			$.messager.alert("提示", "请选择行!", "warning");
			return;
		}
		//新增div
		var body = document.body;
		var div = document.createElement("div");
		div.setAttribute("id", "datagrid_edit_dialog");
		body.appendChild(div);
		//生成dialog,form以及元素
		var dialog_editing = $("#datagrid_edit_dialog");
		var width = 320;
		var height = 500;
		dialog_editing.append("<form class='easyui-form' method='post'></form>");
		if ('width' in param) {
			width = param.width;
		}
		if ('height' in param) {
			height = param.height;
		}
		dialog_editing.dialog({
			width: width,
			height: height,
			modal: true,
			closed: false,
			title: '编辑页面',
			resizable: true,
			onBeforeClose: function () {
				var that = this;
				$.messager.confirm("提示", "关闭编辑框将不会保存输入的内容,确定?", function (r) {
					if (r) {
						$(that).dialog("destroy");
					}
				});
				return false;
			},
			buttons: [
				{ text: '保存', iconCls: 'icon-save', handler: save },
				{ text: '取消', iconCls: 'icon-cancel', handler: cancel }]
		});
		//生成编辑框
		var options = datagrid.datagrid('options');
		var title = "";
		var type = "";
		var field_id = ""
		var dataoptions = "";
		for (i = 0; i < options.columns[0].length; i++) {
			var field = options.columns[0][i];
			title = field.title;
			field_id = field.field;
			if ('input' in field) {
				if ('type' in field.input) {
					type = field.input.type;
				} else {
					continue;
				}
				if ('dataoptions' in field.input) {
					dataoptions = field.input.dataoptions;
				}
			} else {
				continue;
			}
			dialog_editing.find("form").append("<div style='width:100%;height:25px;margin-top:8px;margin-buttom:8px;'>" +
				"<label style='width:90px;text-align:right;'>" + title + ":"
				+ "</label>" + "<input style='height:25px;' name='" + field_id + "' id='" + field_id + "' style='float:left;width:calc(95% - 90px);' class='" + type + "'>" + "</div>");
			$('#' + field_id).attr('data-options', dataoptions);
		}
		$.parser.parse(dialog_editing);
		dialog_editing.window("center");
		dialog_editing.find("form").form('load', row);
		dialog_editing.dialog('open');
		function extend(target, source) {
			for (var obj in source) {
				target[obj] = source[obj];
			}
			return target;
		}
		function save() {
			dialog_editing.find("form").form('submit', {
				url: param.url,
				onSubmit: function (p) {
					p = extend(p, param.extra);
					return $(this).form('validate');
				},
				success: function (data) {
					data = JSON.parse(data);
					if (data.state == 200) {
						$.messager.show({
							title: '成功',
							msg: data.message
						});
						datagrid.datagrid("reload");
						dialog_editing.dialog("destroy");
					} else {
						$.messager.show({
							title: data.message,
							msg: data.message
						});
					}
				},
				onLoadError: function () {
					$.messager.show({
						title: "<p style='color:red;'>错误</p>",
						msg: "无法连接服务器,请检查网络或者重新登录!"
					});
				}
			});
		}
		//取消
		function cancel() {
			$.messager.confirm("提示", "关闭编辑框将不会保存输入的内容,确定?", function (r) {
				if (r) {
					dialog_editing.dialog("destroy");
				}
			});
		}

	},
	initAddDialog: function (jq, param) {
		//width,height,url,extra
		var datagrid = $(jq);
		//新增div
		var body = document.body;
		var div = document.createElement("div");
		div.setAttribute("id", "datagrid_edit_dialog");
		body.appendChild(div);
		//生成dialog,form以及元素
		var dialog_editing = $("#datagrid_edit_dialog");
		var width = 320;
		var height = 500;
		dialog_editing.append("<form class='easyui-form' method='post'></form>");
		if ('width' in param) {
			width = param.width;
		}
		if ('height' in param) {
			height = param.height;
		}
		dialog_editing.dialog({
			width: width,
			height: height,
			modal: true,
			closed: false,
			title: '编辑页面',
			resizable: true,
			onBeforeClose: function () {
				var that = this;
				$.messager.confirm("提示", "关闭编辑框将不会保存输入的内容,确定?", function (r) {
					if (r) {
						$(that).dialog("destroy");
					}
				});
				return false;
			},
			buttons: [
				{ text: '保存', iconCls: 'icon-save', handler: save },
				{ text: '取消', iconCls: 'icon-cancel', handler: cancel }]
		});
		//生成编辑框
		var options = datagrid.datagrid('options');
		var title = "";
		var type = "";
		var field_id = ""
		var dataoptions = "";
		for (i = 0; i < options.columns[0].length; i++) {
			var field = options.columns[0][i];
			title = field.title;
			field_id = field.field;
			if ('input' in field) {
				if ('type' in field.input) {
					type = field.input.type;
				} else {
					continue;
				}
				if ('dataoptions' in field.input) {
					dataoptions = field.input.dataoptions;
				}
			} else {
				continue;
			}
			dialog_editing.find("form").append("<div style='width:100%;height:25px;margin-top:8px;margin-buttom:8px;'>" +
				"<label style='width:90px;text-align:right;'>" + title + ":"
				+ "</label>" + "<input style='height:25px;' name='" + field_id + "' id='" + field_id + "' style='float:left;width:calc(95% - 90px);' class='" + type + "' >" + "</div>");
			$('#' + field_id).attr('data-options', dataoptions);
		}
		$.parser.parse(dialog_editing);
		dialog_editing.window("center");
		dialog_editing.dialog('open');
		function extend(target, source) {
			for (var obj in source) {
				target[obj] = source[obj];
			}
			return target;
		}
		//保存按钮
		function save() {
			dialog_editing.find("form").form('submit', {
				url: param.url,
				onSubmit: function (p) {
					p = extend(p, param.extra);
					return $(this).form('validate');
				},
				success: function (data) {
					data = JSON.parse(data);
					if (data.state == 200) {
						$.messager.show({
							title: '成功',
							msg: data.message
						});
						datagrid.datagrid("reload");
						dialog_editing.dialog("destroy");
					} else {
						$.messager.show({
							title: data.message,
							msg: data.message
						});
					}
				},
				onLoadError: function () {
					$.messager.show({
						title: "<p style='color:red;'>错误</p>",
						msg: "无法连接服务器,请检查网络或者重新登录!"
					});
				}
			});
		}
		//取消
		function cancel() {
			$.messager.confirm("提示", "关闭编辑框将不会保存输入的内容,确定?", function (r) {
				if (r) {
					dialog_editing.dialog("destroy");
				}
			});
		}

	},
	getEditingRowIndexs: function (jq) {
		var rows = $.data(jq[0], "datagrid").panel.find('.datagrid-row-editing');
		var indexs = [];
		rows.each(function (i, row) {
			var index = row.sectionRowIndex;
			if (indexs.indexOf(index) == -1) {
				indexs.push(index);
			}
		});
		return indexs;
	}
});

/**
 * 为tree拓展的弹框编辑节点
 */
$.extend($.fn.tree.methods, {
	extendEdit: function (jq, param) {
		/*
		 * param:state,id,text,pId,url
		 */
		var body = document.body;
		var tree = $(jq);
		var options = $(jq).tree('options');
		var selected = tree.tree("getSelected");
		var parent = null;
		if (!selected) {
			parent = tree.tree('getParent', selected.target).id;
		}
		if (param.state == 'edit') {
			if (!selected) {
				$.messager.alert("提示", "未选中节点！", "warning");
				return;
			}
		}
		if (typeof param == 'string') {

		} else {
			var div = document.createElement("div");
			div.setAttribute("id", "tree_edit_dialog")
			body.appendChild(div);
			var title = "";
			var field_id = "";
			var type = "";
			var dataoptions = "";
			$("#tree_edit_dialog").append("<form class='easyui-form' method='post'></form>");
			for (var i = 0; i < 3; i++) {
				if (i == 0) {
					title = "编号";
					field_id = param.id;
					type = "easyui-textbox";
					dataoptions = "required:true";
				} else if (i == 1) {
					title = "名称";
					field_id = param.text;
					type = "easyui-textbox";
					dataoptions = "required:true";
				} else {
					title = "上级";
					field_id = param.pId;
					type = "easyui-combotree";
					dataoptions = "panelWidth:140,panelHeight:200,required:false,url:\'" + options.url + "\',onClick:function(node){var tree=$(this).combotree(\'tree\').tree(\'getSelected\');" +
						"$(this).combotree(\'setValue\',tree.id)" +
						"}";
				}
				$("#tree_edit_dialog").find("form").append("<div style='width:100%;height:25px;margin-top:8px;margin-buttom:8px;'>" +
					"<label style='width:90px;text-align:right;'>" + title + ":"
					+ "</label>" + "<input style='height:25px;' name='" + field_id +
					"' style='float:left;width:calc(95% - 90px);' class='" +
					type + "' data-options=\"" + dataoptions + "\">" + "</div>");
			}
			$("#tree_edit_dialog").dialog({
				title: "编辑",
				onBeforeClose: function () {
					var that = this;
					$.messager.confirm("提示", "关闭编辑框将不会保存输入的内容,确定?", function (r) {
						if (r) {
							$(that).dialog("destroy");
						}
					});
					return false;
				},
				modal: true,
				width: 300,
				height: 190,
				buttons: [{ text: '保存', iconCls: 'icon-save', handler: save },
				{ text: '取消', iconCls: 'icon-cancel', handler: cancel }]
			});
			$.parser.parse($("#tree_edit_dialog"));
			if (param.state == 'edit') {
				var row1 = {};
				row1[param.id] = selected.id;
				row1[param.text] = selected.text;
				row1[param.pId] = parent;
				$("#tree_edit_dialog").find("form").form('load', row1);
			}
			$("#tree_edit_dialog").window("center");
			//保存按钮
			function save() {
				$("#tree_edit_dialog").find("form").form('submit', {
					url: param.url,
					onSubmit: function (p) {
						p[param.pId] == p[param.pId] === "" ? null : p[param.pId];
						return $(this).form('validate');
					},
					success: function (data) {
						data = JSON.parse(data);
						if (data.state == 200) {
							$.messager.show({
								title: '成功',
								msg: data.message
							});
							tree.tree("reload");
							$("#tree_edit_dialog").dialog("destroy");
						} else {
							$.messager.show({
								title: data.message,
								msg: data.message
							});
						}
					},
					onLoadError: function () {
						$.messager.show({
							title: "<p style='color:red;'>错误</p>",
							msg: "无法连接服务器,请检查网络或者重新登录!"
						});
					}
				});
			}
			//取消按钮
			function cancel() {
				$.messager.confirm("提示", "关闭编辑框将不会保存输入的内容,确定?", function (r) {
					if (r) {
						$("#tree_edit_dialog").dialog("destroy");
					}
				});
			}
		}
	}
});

//表单转json
$.fn.serializeObject = function () {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function () {
		if (o[this.name]) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

/***
 * 自定义验证
 */
/**
 * auther by Highness
 * date : xxxx-xx-xx
 */


// 时间格式规范
var regex_dateTime = /\d{4}\-\d{2}\-\d{2} \d{2}\:\d{2}:\d{2}/;//@author ren

$.extend($.fn.validatebox.defaults.rules, {

	// 字符最大长度（param传参）
	maxLength: {

		validator: function (value, param) {

			return value.length <= param[0];

		},

		message: '您输入的字数太长了,最多{0}个字'

	},

	//最大值判断
	max: {
		validator: function (value, param) {
			return value <= param[0]
		},
		message: '请输入一个最大为{0}的值'
	},

	//最小值判断
	min: {
		validator: function (value, param) {
			return value >= param[0]
		},
		message: '请输入一个最小为{0}的值'
	},

	// 验证姓名，可以是中文或英文

	name: {

		validator: function (value) {

			return /^[\u0391-\uFFE5]{1,20}$/i.test(value) | /^\w+[\w\s]+\w+$/i.test(value);

		},

		message: '姓名字数过多或应为中文或者英文'

	},

	// 验证身份证

	idcard: {

		validator: function (value) {

			return /^\d{15}(\d{2}[Xx0-9])?$/i.test(value);

		},

		message: '身份证应为15位或者18位'

	},

	// 验证IP地址
	ip: {
		validator: function (value) {
			return /\d+\.\d+\.\d+\.\d+/.test(value);
		},
		message: 'IP地址格式不正确'
	},

	//年龄验证
	age: {

		validator: function (value) {

			return /^[0-9]{1,2}$/i.test(value);//0-99

		},

		message: '您输入的年龄不合法'

	},

	// 验证电话号码
	phone: {

		validator: function (value) {

			return /^1\d{10}$/i.test(value) || /^0\d{2,3}-?\d{7,8}$/i.test(value);

		},

		message: '电话号码正确格式:15288888888或020(0310)-88888888'

	},

	// 验证数字,整数或小数
	number: {

		validator: function (value) {

			return /^\d{1,10}(\.\d{0,4})?$/i.test(value);

		},

		message: '请输入正确的金额'

	},

	// 验证数字,只能为整数
	integer: {

		validator: function (value) {

			return /^\d{1,12}$/i.test(value);

		},

		message: '请输入一个整数'

	},


	// 时间验证
	//@author ren
	/* start */
	endToStart: {

		validator: function (value, param) {

			return value > $("#" + param[0] + " input[name='" + param[1] + "']").val();//结束时间>开始时间

		},

		message: '结束时间应晚于起始时间'

	},

	startToEnd: {

		validator: function (value, param) {

			return value > $("#" + param[0]).datetimebox('getValue');//结束时间>开始时间

		},

		message: '结束时间应晚于起始时间'

	},

	datetimeValidate: {

		validator: function (value, param) {

			return regex_dateTime.test(value);//验证时间格式是否规范

		},

		message: '时间格式应为 2015-01-01 12:00:00'

	}
	/* end */
});





